package org.apache.ibatis.usage.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @Name ReflectionUtils
 * @Description: 反射工具类
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-04-24 16:54:28
 **/
public class ReflectionUtils {

    /**
     * 比较两个相同类型对象的属性差异
     *
     * @param o1 第一个对象
     * @param o2 第二个对象
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @version v1.0.0
     * @author lichao
     * @date 2024-04-24 16:55:21
     */
    public static Map<String, String> diffObject(Object o1, Object o2) {
        Map<String, String> diffMap = new HashMap<>();
        try {
            Class<?> o1Class = o1.getClass();
            Class<?> o2Class = o2.getClass();
            if (o1Class.equals(o2Class)) {
                Field[] fields = o1Class.getDeclaredFields();
                for (Field field : fields) {
                    // 设置所有属性均可被反射访问
                    field.setAccessible(true);
                    // 获取当前属性的值
                    Object o1Value = field.get(o1);
                    Object o2Value = field.get(o2);
                    if ((o1Value == null && o2Value != null) || (o1Value != null && !o1Value.equals(o2Value))) {
                        diffMap.put(field.getName(), "o1Value [" + o1Value + "] -> o2Value [" + o2Value + "]");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return diffMap;
    }

}

